//
//  ViewB.m
//  drag
//
//  Created by 梁羽 on 2025/6/28.
//

#import "ViewB.h"
#import "ViewA.h"

@implementation ViewB

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.minSize = 60;
        
        // 初始化椭圆样式
        _ellipseBorderColor = [UIColor redColor];
        _ellipseBorderWidth = 2.0;
        
        // 初始化控制矩形
        _controlRect = CGRectInset(self.bounds, 20, 20);
        _ellipseRect = _controlRect;
        
        // 添加拖动手势
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:panGesture];
        
        // 添加边框以便更好地区分视图
        self.layer.borderWidth = 1.0;
        self.layer.borderColor = [UIColor blackColor].CGColor;
        
        // 添加四个角的调整按钮
        [self setupResizeButtons];
    }
    return self;
}

- (void)setupResizeButtons {
    NSMutableArray *buttons = [NSMutableArray array];
    
    for (NSInteger i = 0; i < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 30, 30);
        button.backgroundColor = [UIColor orangeColor];
        button.layer.cornerRadius = 15;
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor blackColor].CGColor;
        button.tag = i;
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleResizePan:)];
        [button addGestureRecognizer:panGesture];
        
        [buttons addObject:button];
        [self addSubview:button];
    }
    
    self.resizeButtons = [buttons copy];
    [self updateResizeButtonPositions];
}

- (void)updateResizeButtonPositions {
    self.resizeButtons[0].center = CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMinY(_controlRect));
    self.resizeButtons[1].center = CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMinY(_controlRect));
    self.resizeButtons[2].center = CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMaxY(_controlRect));
    self.resizeButtons[3].center = CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMaxY(_controlRect));
    _ellipseRect = _controlRect;
    
    // 更新菜单栏位置
    if ([self.containerView isKindOfClass:[ViewA class]]) {
        [(ViewA *)self.containerView updateMenuBarPosition];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    // 绘制控制矩形
    _rectanglePath = [UIBezierPath bezierPath];
    [_rectanglePath moveToPoint:CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMinY(_controlRect))];
    [_rectanglePath addLineToPoint:CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMinY(_controlRect))];
    [_rectanglePath moveToPoint:CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMinY(_controlRect))];
    [_rectanglePath addLineToPoint:CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMaxY(_controlRect))];
    [_rectanglePath moveToPoint:CGPointMake(CGRectGetMaxX(_controlRect), CGRectGetMaxY(_controlRect))];
    [_rectanglePath addLineToPoint:CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMaxY(_controlRect))];
    [_rectanglePath moveToPoint:CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMaxY(_controlRect))];
    [_rectanglePath addLineToPoint:CGPointMake(CGRectGetMinX(_controlRect), CGRectGetMinY(_controlRect))];
    
    [[UIColor greenColor] setStroke];
    _rectanglePath.lineWidth = 2.0;
    [_rectanglePath stroke];
    
    // 绘制椭圆形（透明填充）
    _ellipsePath = [UIBezierPath bezierPathWithOvalInRect:_ellipseRect];
    
    [[UIColor clearColor] setFill]; // 设置透明填充
    [_ellipsePath fill];
    
    [self.ellipseBorderColor setStroke]; // 使用可变的边框颜色
    _ellipsePath.lineWidth = self.ellipseBorderWidth; // 使用可变的边框粗细
    [_ellipsePath stroke];
}

- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        _panStartLocation = [gesture locationInView:self.superview];
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint currentLocation = [gesture locationInView:self.superview];
        CGPoint translation = CGPointMake(currentLocation.x - _panStartLocation.x,
                                         currentLocation.y - _panStartLocation.y);
        
        CGPoint newCenter = CGPointMake(self.center.x + translation.x,
                                       self.center.y + translation.y);
        
        CGFloat minX = self.frame.size.width / 2;
        CGFloat maxX = self.containerView.frame.size.width - self.frame.size.width / 2;
        CGFloat minY = self.frame.size.height / 2;
        CGFloat maxY = self.containerView.frame.size.height - self.frame.size.height / 2;
        
        newCenter.x = MAX(minX, MIN(newCenter.x, maxX));
        newCenter.y = MAX(minY, MIN(newCenter.y, maxY));
        
        self.center = newCenter;
        _panStartLocation = currentLocation;
        
        // 更新菜单栏位置
        if ([self.containerView isKindOfClass:[ViewA class]]) {
            [(ViewA *)self.containerView updateMenuBarPosition];
        }
    }else if (gesture.state == UIGestureRecognizerStateEnded ||
              gesture.state == UIGestureRecognizerStateCancelled) {
         // 拖拽结束时获取当前椭圆路径并回调
         [self notifyEllipsePathUpdate];
     }
}

- (void)handleResizePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateChanged) {
        UIButton *button = (UIButton *)gesture.view;
        CGPoint translation = [gesture translationInView:self];
        
        CGPoint newButtonCenter = CGPointMake(button.center.x + translation.x,
                                            button.center.y + translation.y);
        
        CGRect newControlRect = _controlRect;
        switch (button.tag) {
            case 0: { // 左上
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newControlRect.origin.x += deltaX;
                newControlRect.origin.y += deltaY;
                newControlRect.size.width -= deltaX;
                newControlRect.size.height -= deltaY;
                break;
            }
            case 1: { // 右上
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newControlRect.origin.y += deltaY;
                newControlRect.size.width += deltaX;
                newControlRect.size.height -= deltaY;
                break;
            }
            case 2: { // 左下
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newControlRect.origin.x += deltaX;
                newControlRect.size.width -= deltaX;
                newControlRect.size.height += deltaY;
                break;
            }
            case 3: { // 右下
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newControlRect.size.width += deltaX;
                newControlRect.size.height += deltaY;
                break;
            }
        }
        
        newControlRect.size.width = MAX(20, newControlRect.size.width);
        newControlRect.size.height = MAX(20, newControlRect.size.height);
        
        CGFloat margin = 20;
        CGRect newBFrame = CGRectInset(newControlRect, -margin, -margin);
        newBFrame.size.width = MAX(self.minSize, newBFrame.size.width);
        newBFrame.size.height = MAX(self.minSize, newBFrame.size.height);
        newBFrame.size.width = MIN(self.containerView.bounds.size.width, newBFrame.size.width);
        newBFrame.size.height = MIN(self.containerView.bounds.size.height, newBFrame.size.height);
        
        CGPoint oldCenter = self.center;
        self.frame = newBFrame;
        self.center = oldCenter;
        
        CGRect containerBounds = self.containerView.bounds;
        if (CGRectGetMinX(self.frame) < 0) {
            self.frame = CGRectMake(0, CGRectGetMinY(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMinY(self.frame) < 0) {
            self.frame = CGRectMake(CGRectGetMinX(self.frame), 0,
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMaxX(self.frame) > containerBounds.size.width) {
            self.frame = CGRectMake(containerBounds.size.width - CGRectGetWidth(self.frame),
                                  CGRectGetMinY(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMaxY(self.frame) > containerBounds.size.height) {
            self.frame = CGRectMake(CGRectGetMinX(self.frame),
                                  containerBounds.size.height - CGRectGetHeight(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        
        _controlRect = CGRectInset(self.bounds, margin, margin);
        
        [gesture setTranslation:CGPointZero inView:self];
        [self updateResizeButtonPositions];
        [self setNeedsDisplay];
    }else if (gesture.state == UIGestureRecognizerStateEnded ||
              gesture.state == UIGestureRecognizerStateCancelled) {
         // 调整大小结束时获取当前椭圆路径并回调
         [self notifyEllipsePathUpdate];
     }
}

// 新增方法：通知椭圆路径更新
- (void)notifyEllipsePathUpdate {
    UIBezierPath *ellipsePath = [self currentEllipsePathInView:self.containerView];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"8888-9999" object:nil userInfo:@{@"path": ellipsePath, @"type": @"1"}];
}

- (UIBezierPath *)currentEllipsePathInView:(UIView *)view {
    // 将椭圆路径转换为目标视图坐标系
    CGRect ellipseRect = [self convertRect:self.ellipseRect toView:view];
    return [UIBezierPath bezierPathWithOvalInRect:ellipseRect];
}

@end
